package com.itheima.reggie.controller;

import com.github.wxpay.sdk.WXPayUtil;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * @author:YZN
 * @date:2023/1/7
 * @description:
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Resource
    private OrderService orderService;

    @Resource
    private HttpServletRequest request;

    @Resource
    private HttpServletResponse response;

    @GetMapping("/page")
    public R orderPage(@RequestParam("page") Integer page,
                       @RequestParam("pageSize") Integer pageSize,
                       @RequestParam(value = "number",required = false) String number,
                       @RequestParam(value = "beginTime",required = false) String beginTime,
                       @RequestParam(value = "endTime",required = false) String endTime){
        return orderService.orderPage(page,pageSize,number,beginTime,endTime);
    }

    @GetMapping("/userPage")
    public R userPage(@RequestParam("page") Integer page,
                      @RequestParam("pageSize") Integer pageSize){
        return orderService.userPage(page,pageSize);
    }

    @PostMapping("/submit")
    public R submit(@RequestBody Orders order) {
        return orderService.submit(order);
    }

    @PostMapping("/notify")
    public void notifyOfWx() throws Exception {
        ServletInputStream is = request.getInputStream();
        StringBuilder sb = new StringBuilder();

        Integer len;
        byte[] bytes = new byte[2048];
        while ((len = is.read(bytes)) != -1) {
            sb.append(new String(bytes,0,len));
        }
        String result = sb.toString();
        Map<String, String> map = WXPayUtil.xmlToMap(result);

        if (!map.get("result_code").equals("SUCCESS")){
            throw new RuntimeException("支付失败，进行人工处理");
        }
        String orderId = map.get("out_trade_no");

        //更新数据库数据即可
        orderService.updateById(orderId);



        //需要更新微信调用的信息，来修改订单的状态为已支付
        //给微信支付一个成功的响应
        response.setContentType("text/xml");
        String data = "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        response.getWriter().write(data);


    }
    //查询订单的状态信息
    @GetMapping("/findStatusById")
    public R findStatusById(String orderId){

        //1.根据Id查询订单状态
        Orders order = orderService.getById(orderId);

        //2.判断状态是否为2
        if(order.getStatus() == 2){

            return R.success("支付成功");//code = 1
        }
        //3.如果状态为已支付。直接跳转 返回code 1
        return R.error("等待支付"); //code = 0

    }
}
